
package net.atremmedia.gwt.actionjava.examples.basics.samples;

import net.atremmedia.gwt.actionjava.examples.AJExample;
import net.atremmedia.gwt.actionjava.examples.frame.AJExampleOverview;
import actionjava.display.Graphics;
import actionjava.display.Shape;
import actionjava.events.tick.TickEvent;

public class Bouncing1 extends AJExample
{
	public static final String NAME = "Bouncing 1";
	public static final String DESCRIPTION = "Description";
	public static final String EXAMPLE_SRC = "https://code.google.com/p/gwt-actionjava/source/browse/trunk/aj-examples/aj-examples-basics/src/main/java/net/atremmedia/gwt/actionjava/examples/basics/samples/Bouncing1.java";

	private Shape ball;
	private double vx = 0;
	private double vy = 0;
	private double radius = 50;

	public Bouncing1(AJExampleOverview base)
	{
		super(NAME, DESCRIPTION, EXAMPLE_SRC, base);
	}

	private void initialize()
	{
		vx = 0;
		vy = 0;
	}

	@Override
	public void run()
	{
		initialize();
		createBall();

		ball.setX(getWidth() / 2);
		ball.setY(getHeight() / 2);
		vx = Math.random() * 10 - 5;
		vy = Math.random() * 10 - 5;
		addChild(ball);
	}

	private Shape createBall()
	{
		ball = new Shape();
		ball.setX(50);
		ball.setY(100);

		Graphics graphs = ball.getGraphics();
		graphs.beginFill(getRandomColor());
		graphs.drawCircle(0, 0, radius);
		graphs.endFill();

		return ball;
	}

	@Override
	public void onRenderTick(TickEvent event)
	{
		ball.addX(vx);
		ball.addY(vy);
		double left = 0;
		double right = getWidth();
		double top = 0;
		double bottom = getHeight();

		if(ball.getX() + radius > right) {
			ball.setX(right - radius);
			vx *= -1;

		} else if(ball.getX() - radius < left) {
			ball.setX(left + radius);
			vx *= -1;

		}

		if(ball.getY() + radius > bottom) {
			ball.setY(bottom - radius);
			vy *= -1;

		} else if(ball.getY() - radius < top) {
			ball.setY(top + radius);
			vy *= -1;

		}
	}
}
